<docs>
  <docs-title> chart 初始化 </docs-title>
  <docs-desc> 全局配置: theme、backgroundColor、grid、tooltip、监听resize </docs-desc>
 </docs>

<template>
  <div class="chart"></div>
</template>

<script>
import * as echarts from "echarts";
import _ from "lodash";

export default {
  props: {
    options: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      chart: null,
      commonOptions: null
    };
  },
  watch: {
    options: {
      handler: function () {
        this.setOption();
      },
      deep: true
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      let chartDom = this.$el;
      this.chart = echarts.init(chartDom, "light");

      window.addEventListener("resize", this.resize);

      this.setOption();
    },
    setOption() {
      let baseOptions = {
        backgroundColor: "rgba(0,0,0,0)",
        grid: {
          top: "20px",
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        tooltip: {
          trigger: "axis"
        }
      };

      let options = _.merge(baseOptions, this.commonOptions, this.options);

      options = this.handlerOptions(options) || options;

      if (options && this.chart) {
        this.chart.setOption(options);
      }
    },
    getCharts() {
      return this.chart;
    },
    resize() {
      this.chart?.resize();
    },
    dispose() {
      if (this.chart) {
        this.chart.dispose();
      }

      window.removeEventListener("resize", this.resize);
    },
    // 用于拿到完整的 options 后，做处理后再 setOption 输入输出为 options 对象
    handlerOptions() {}
  },
  beforeDestroy() {
    this.dispose();
  }
};
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
  position: relative;
  min-height: 100px;
  min-width: 100px;
}
</style>
